package com.adcc.loadsheet.billing.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.exception.ParamValidException;
import com.adcc.loadsheet.billing.exception.PermissionVerifyException;
import com.adcc.loadsheet.billing.security.UserInfo;
import com.adcc.loadsheet.billing.service.ContractUserService;
import com.adcc.loadsheet.billing.service.PermissionService;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.vo.ResultStatus;
import com.adcc.loadsheet.billing.vo.ResultVO;
import com.adcc.loadsheet.billing.vo.TreeVO;
import com.adcc.loadsheet.billing.vo.contractuser.ContractUserEntityVO;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 权限管理Controller层
 * Created by zhaoml on 2020/9/22.
 */
@Controller
@RequestMapping(value = "permission")
@Api(value = "/permission", description = "权限管理相关操作controller")
public class PermissionController extends BasisController{

    @Autowired
    PermissionService permissionService;

    @Autowired
    ContractUserService contractUserService;

    /**
     * 进入权限管理页面
     * @param model
     * @return
     */
    @PreAuthorize("hasPermission('','PermissionManage')")
    @GetMapping(value = "topermissionmanage")
    @ApiOperation(value = "/topermissionmanage", notes = "跳转到权限管理页面", httpMethod = "GET")
    public String toPermissionManage(Model model) {
        //将合同用户列表传到页面，用以选择
        // 合同用户关联的普通用户（并授权此功能菜单）可以查询当前合同的用户的舱单计费统计账单，管理员可以查询全部合同用户的计费统计账单
        Map<String, Object> map = Maps.newHashMap();
        UserInfo userInfo = userContext.getCurrentUser();
        if(!userInfo.isSuperAdmin()){
            map.put("PB_LOGIN_ID",userInfo.getUsername());
        }
        List<ContractUserEntity> contractUserList = contractUserService.select(map);
        model.addAttribute("contractUserList", contractUserList);
        return "permission/permission-manage";
    }

    //查询合同用户
    @PostMapping(value = "findContractUsers", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/findContractUsers", notes = "查询合同用户", httpMethod = "POST")
    @ResponseBody
    public ResultVO findContractUsers(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            Map<String, Object> paramMap = inputContractUserParams(map);
            PageInfo<ContractUserEntityVO> contractUserEntityVOPageInfo = permissionService.selectContractUserForPage(paramMap);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("voList", contractUserEntityVOPageInfo);
        } catch (Exception ex) {
            Log.error(PermissionController.class, "查询合同用户出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query findContractUsers", ex.fillInStackTrace()));
            LogUtil.errorLog(PermissionController.class,ex,"findContractUsers()");
        }
        return vo;
    }

    //获取关联权限Tree，并设置是否选中
    @PostMapping(value = "getPermissionsTree", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/getPermissionsTree", notes = "获取关联权限Tree", httpMethod = "POST")
    public @ResponseBody
    List<TreeVO> getPermissionsTree(@RequestBody ContractUserEntityVO contractUserEntityVO) {
        List<TreeVO> list = Lists.newArrayList();
        try {
            Integer contractUserId = contractUserEntityVO.getContractUserId();
            list = permissionService.getPermissionsTreeNode(contractUserId);
        } catch (Exception ex) {
            Log.error(PermissionController.class, "获取关联权限Tree出错", ex);
        }
        return list;
    }

    //编辑权限
    @PostMapping(value = "editPermissions", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/editPermissions", notes = "编辑权限", httpMethod = "POST")
    @ResponseBody
    public ResultVO editPermissions(@RequestBody ContractUserEntityVO contractUserEntityVO) {
        ResultVO vo = new ResultVO();
        try {
            //编辑权限(包含PB_LOGIN_ID、permissionIds)
            permissionService.editPermissions(contractUserEntityVO.getContractUserId(),contractUserEntityVO.getPermissionIds());
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("msg", "编辑权限成功！");
        } catch (Exception ex) {
            Log.error(PermissionController.class, "编辑权限出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason("编辑权限失败！");
            LogUtil.errorLog(PermissionController.class, ex, "editPermissions()");
        }
        return vo;
    }

    //通过类型获取合同用户
    @PostMapping(value = "getContractUsersByUserType", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/getContractUsersByUserType", notes = "通过类型获取合同用户", httpMethod = "POST")
    @ResponseBody
    public ResultVO getContractUsersByUserType(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            UserInfo userInfo = userContext.getCurrentUser();
            if(!userInfo.isSuperAdmin()){
                map.put("PB_LOGIN_ID",userInfo.getUsername());
            }
            List<ContractUserEntity> contractUserList = contractUserService.select(map);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("contractUserList", contractUserList);
        } catch (Exception ex) {
            Log.error(PermissionController.class, "通过类型获取合同用户出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query getContractUsersByUserType", ex.fillInStackTrace()));
            LogUtil.errorLog(PermissionController.class,ex,"getContractUsersByUserType()");
        }
        return vo;
    }

    private Map<String, Object> inputContractUserParams(Map<String, Object> map) throws
            PermissionVerifyException, ParamValidException {
        Map<String, Object> paramMap = Maps.newHashMap();
        try {
            //合同用户
            Integer contractUserId = map.get("contractUserId") == null || "".equals(map.get("contractUserId")) ? null : Integer.parseInt(map.get("contractUserId").toString());
            //类型
            Integer userType = map.get("userType") == null || "".equals(map.get("userType")) ? null : Integer.parseInt(map.get("userType").toString());
            //第几页
            Integer pageNum = map.get("pageNum") == null || "".equals(map.get("pageNum")) ? 1 : Integer.parseInt(map.get("pageNum").toString());
            //每页页数
            Integer pageSize = map.get("pageSize") == null || "".equals(map.get("pageSize")) ? PAGE_SIZE_DEFAULT : Integer.parseInt(map.get("pageSize").toString());

            paramMap.put("contractUserId", contractUserId);
            paramMap.put("userType", userType);
            paramMap.put("pageNum", pageNum);
            paramMap.put("pageSize", pageSize);
        } catch (Exception e) {
            throw new ParamValidException("输入参数错误");
        }
        return paramMap;
    }
}